using System.Collections.Generic;

namespace Infralution.Localization.Wpf
{
	/// <summary>
	/// Defines a class for managing <see cref="T:Infralution.Localization.Wpf.ManagedMarkupExtension" /> objects
	/// </summary>
	/// <remarks>
	/// This class provides a single point for updating all markup targets that use the given Markup 
	/// Extension managed by this class.   
	/// </remarks>
	public class MarkupExtensionManager
	{
		private List<ManagedMarkupExtension> list_0 = new List<ManagedMarkupExtension>();

		private int int_0;

		private int int_1 = 40;

		/// <summary>
		/// Return a list of the currently active extensions
		/// </summary>
		public List<ManagedMarkupExtension> ActiveExtensions => list_0;

		/// <summary>
		/// Create a new instance of the manager
		/// </summary>
		/// <param name="cleanupInterval">
		/// The interval at which to cleanup and remove extensions associated with garbage
		/// collected targets.  This specifies the number of new Markup Extensions that are
		/// created before a cleanup is triggered
		/// </param>
		public MarkupExtensionManager(int cleanupInterval)
		{
			int_1 = cleanupInterval;
		}

		/// <summary>
		/// Force the update of all active targets that use the markup extension
		/// </summary>
		public virtual void UpdateAllTargets()
		{
			foreach (ManagedMarkupExtension item in list_0)
			{
				item.UpdateTargets();
			}
		}

		/// <summary>
		/// Cleanup references to extensions for targets which have been garbage collected.
		/// </summary>
		/// <remarks>
		/// This method is called periodically as new <see cref="T:Infralution.Localization.Wpf.ManagedMarkupExtension" /> objects 
		/// are registered to release <see cref="T:Infralution.Localization.Wpf.ManagedMarkupExtension" /> objects which are no longer 
		/// required (because their target has been garbage collected).  This method does
		/// not need to be called externally, however it can be useful to call it prior to calling
		/// GC.Collect to verify that objects are being garbage collected correctly.
		/// </remarks>
		public void CleanupInactiveExtensions()
		{
			List<ManagedMarkupExtension> list = new List<ManagedMarkupExtension>(list_0.Count);
			foreach (ManagedMarkupExtension item in list_0)
			{
				if (item.IsTargetAlive)
				{
					list.Add(item);
				}
			}
			list_0 = list;
		}

		internal void method_0(ManagedMarkupExtension managedMarkupExtension_0)
		{
			if (int_0 > int_1)
			{
				CleanupInactiveExtensions();
				int_0 = 0;
			}
			list_0.Add(managedMarkupExtension_0);
			int_0++;
		}
	}
}
